package com.eet.juc.utils;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 加法计数器Demo
 *
 * @author zheng.zhang
 */
@SuppressWarnings("all")
public class CyclicBarrierDemo {
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(7);

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(7, () -> {
            System.out.println("集齐七颗龙珠, 召唤神龙成功!");
            // EXECUTOR_SERVICE.shutdownNow();
        });

        // 创建七条线程开始集齐七颗龙珠
        for (int i = 0; i < 7; i++) {
            final int tempI = i + 1;
            EXECUTOR_SERVICE.submit(() -> {
                System.out.println(Thread.currentThread().getName().concat(" -> 收集到第" + tempI + "颗龙珠"));

                try {
                    // 线程等待, 等待计数器满足条件并且执行计数器后面的线程
                    barrier.await();
                    EXECUTOR_SERVICE.shutdownNow();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
